"use strict";
import * as React from 'react';
import { autoSize, commonProps, commonStyles } from "../../assets/styles/common";
const { connect } = require('react-redux');
const NavigationBar = require('react-native-navbar').default;
const { Actions } = require("react-native-router-flux");
import NavRightButton from "../../component/RightButton";
import SearchBar from "../../component/SearchBar";
import MyText from "../../component/MyText";
import DynamicItem from "../../component/DynamicItem";
import MyIcon from "../../component/icon";
import { SCREEN_WIDTH, } from "../../constant";
import GroupPage from "./GroupPage";
import ActiveList from "./ActiveList";
import constant from "../../utils/constant";
const { Tabs, WhiteSpace, List } = require('antd-mobile');
const { View, FlatList, Image, TouchableOpacity, Animated, DeviceEventEmitter, NativeModules } = require('react-native');
const Notice = NativeModules.Notice;
class Community extends React.Component {
    constructor(props, context) {
        super(props, context);
        this.onEnter = (e) => {
            if (this.state.currentTab === 1) {
                DeviceEventEmitter.emit(constant.noticeKeyOfRefreshGroups);
            }
            if (this.state.currentTab === 2) {
                DeviceEventEmitter.emit(constant.noticeKeyOfEnterActiveList);
            }
            else {
                this.props.dispatch({ type: 'auth/fetchData', payload: { pi: 1, ps: 5 } });
            }
        };
        this.onDynamicReachedEnd = () => {
            if (!this.props.post.list.last) {
                this.props.dispatch({
                    type: 'post/fetchData',
                    payload: {
                        pi: this.props.post.list.number + 2,
                        ps: 5,
                        loadmore: true,
                        areaId: this.props.auth.selectArea.id
                    }
                });
            }
        };
        this.onSelectArea = (selectArea) => {
            this.props.dispatch({
                type: 'auth/changeSelectArea',
                payload: { selectArea, pi: 1, ps: 5 }
            });
            this.showAll();
        };
        this.showAll = () => {
            this.setState({ showAll: !this.state.showAll });
        };
        this.goToTab = (currentTab) => {
            if (this.state.currentTab === currentTab)
                return;
            this.setState({ currentTab });
            Animated.timing(this.state.tabBarUnderlinePosition, {
                toValue: currentTab * SCREEN_WIDTH / 3,
                duration: 300,
            }).start();
            if (currentTab === 0) {
            }
            if (currentTab === 1) {
            }
            if (currentTab === 2) {
            }
        };
        this.onPraise = (type, item) => {
            this.props.dispatch({
                type: 'post/praise',
                payload: {
                    type,
                    typeId: item.id,
                    item
                }
            });
        };
        this.onRefresh = () => {
            this.props.dispatch({ type: 'auth/fetchData', payload: { pi: 1, ps: 5 } });
        };
        this.goToDynamicDetail = (dynamicItem) => {
            this.props.dispatch({
                type: 'post/detail',
                payload: { dynamicItem }
            });
        };
        this.renderTabs = (props) => {
            return (<View style={[commonStyles.tabBar]}>
                {props.tabs.map((item, index) => {
                return (<TouchableOpacity key={index} style={commonStyles.tabBarItem} onPress={this.goToTab.bind(this, index)}>
                            {item.icon ? <MyIcon name={item.icon} color={this.state.currentTab === index ? '#DAC228' : '#AEADAD'}/> : null}
                            <MyText style={this.state.currentTab === index ? commonStyles.tabBarItemTextActive : commonStyles.tabBarItemTextNormal}>{item.title}</MyText>
                        </TouchableOpacity>);
            })}
                <Animated.View style={[commonStyles.tabBarUnderline, {
                    left: this.state.tabBarUnderlinePosition,
                    width: SCREEN_WIDTH / 3
                }]}/>
            </View>);
        };
        this.renderContent = (props) => {
            switch (props.key) {
                case 0:
                    return this.renderDynamic();
                case 1:
                    return <GroupPage />;
                case 2:
                    return <ActiveList />;
            }
        };
        this.state = {
            currentTab: 0,
            tabBarUnderlinePosition: new Animated.Value(0),
            showAll: false,
        };
    }
    componentDidMount() {
        this.props.dispatch({ type: 'auth/fetchData', payload: { pi: 1, ps: 10 } });
        DeviceEventEmitter.addListener(constant.noticeKeyOfEnterCommunity, this.onEnter);
        DeviceEventEmitter.emit(constant.noticeKeyOfSubscriptMessage, {
            sender: this.props.auth.userInfo.account
        });
        DeviceEventEmitter.emit(constant.noticeKeyOfSubscriptMessage, {
            subscriptUrl: constant.subscriptNoticeUrl
        });
        Notice.joinWifi({ ssid: "phonesun", passphrase: "fengxian2017", isWEP: false }).then(e => {
            console.log('success', e);
        }).catch(e => {
            console.log("error", e);
        });
    }
    componentWillUnmount() {
        DeviceEventEmitter.removeListener(constant.noticeKeyOfEnterCommunity);
    }
    renderDynamicHeader() {
        return (<View>
                <View style={[commonStyles.listItem, { padding: 20, backgroundColor: '#F4F4F4' }]}>
                    <MyText style={{ color: '#333', fontSize: 16 }}>查看帖子</MyText>
                    <TouchableOpacity style={[commonStyles.listItem]} onPress={this.showAll}>
                        <MyText style={{
            color: '#000',
            fontSize: 16
        }}>{this.props.auth.selectArea ? this.props.auth.selectArea.name : ''}</MyText>
                        <MyIcon name='icon-xiangxia' color={'#000'}/>
                    </TouchableOpacity>
                </View>
                {this.state.showAll ?
            <List>
                        {this.props.auth.areaList.map((item, index) => (<List.Item style={{ backgroundColor: '#F4F4F4' }} key={index} onClick={this.onSelectArea.bind(this, item)}>
                                    <MyText>{item.name}</MyText>
                                </List.Item>))}
                    </List>
            : null}
            </View>);
    }
    renderDynamic() {
        return (<View style={[commonStyles.flex1]}>
                <TouchableOpacity style={[commonStyles.listItem, { padding: 10, backgroundColor: '#fff' }]} onPress={Actions.newPostings.bind(this, { postType: 'post' })}>
                    <Image source={require('../../assets/image/avatar_six.png')} width={autoSize(35)} height={autoSize(35)}/>
                    <MyText style={{ color: '#999', fontSize: 16, marginLeft: 10 }}>您在想什么?</MyText>
                </TouchableOpacity>

                <FlatList data={this.props.post.list ? this.props.post.list.content : []} renderItem={({ item }) => <DynamicItem item={item} onCommentPress={this.goToDynamicDetail.bind(this, item)} onUserInfoPress={company => Actions.companyInfo({ company })} onContentPress={this.goToDynamicDetail.bind(this, item)} onLikePress={this.onPraise.bind(this, 'post')}/>} ListHeaderComponent={this.renderDynamicHeader.bind(this)} keyboardDismissMode='on-drag' keyExtractor={(item, index) => index} extraData={this.state} onRefresh={this.onRefresh} refreshing={this.props.post.loading} onEndReachedThreshold={1} onEndReached={this.onDynamicReachedEnd} ItemSeparatorComponent={() => <WhiteSpace />}/>
            </View>);
    }
    render() {
        return (<View style={[commonStyles.container]}>
                
                <NavigationBar {...commonProps.navBar} rightButton={<NavRightButton icon={{
            name: 'icon-tixing',
            color: '#999999',
            size: 25,
            badgeNumber: this.props.message.list.length
        }} onPress={Actions.notice}/>} title={<SearchBar placeholder='探索会员圈' rightButtonWidth={60} editable={false} onPress={Actions.search}/>}/>

                <Tabs tabBarBackgroundColor="red" tabBarUnderlineStyle={{ backgroundColor: '#DAC228' }} tabBarInactiveTextColor="#999" tabBarActiveTextColor="#DAC228" useOnPan={false} swipeable={false} initialPage={0} page={this.state.currentTab} renderTabBar={this.renderTabs} tabs={[
            { title: '最新动态', key: 0 },
            { title: '群组', key: 1 },
            { title: '活动', key: 2 },
        ]}>
                    {this.renderContent}
                </Tabs>
            </View>);
    }
}
export default connect(({ auth, post, message }) => ({ auth, post, message }))(Community);
